package com.working.libcommon.adapter

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingSource

internal class LawWitPagingSource<T : Any>(
    val start: Int,
    private val producer: suspend (PagedListReqBean) -> List<T>?
) :
    PagingSource<Int, T>() {
    private val pagedListReqBean = PagedListReqBean()
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, T> {
        return try {
            val page = params.key ?: start
            //获取网络数据
            pagedListReqBean.pageNo = page
            pagedListReqBean.pageSize = params.loadSize
            val result = producer.invoke(pagedListReqBean)
            val nextKey = if ((result?.size ?: 0) == 0) null else page + 1
            LoadResult.Page(
                //需要加载的数据
                data = result ?: emptyList(),
                //如果可以往上加载更多就设置该参数，否则不设置
                prevKey = null,
                //加载下一页的key 如果传null就说明到底了
                nextKey = nextKey
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}

class PagingDataSource<T : Any>(
    startPageNumber: Int = 0,
    pageSize: Int = 10,
    initialLoadSize: Int = pageSize * 2,
    private val producer: suspend (PagedListReqBean) -> List<T>?
) {
    private val pager by lazy {
        Pager(PagingConfig(pageSize = pageSize, initialLoadSize = initialLoadSize)) {
            LawWitPagingSource(startPageNumber, producer)
        }
    }

    val flow = pager.flow
}